import { ref, computed } from "vue";
import { defineStore } from "pinia";
import {
  addToCratAPI,
  loadCartAPI,
  delFromCartAPI,
} from "../server/shop-carts";

export const useCart = defineStore("cart", () => {
  // 定义一个数据存储购物车列表
  const carts = ref([]);
  // 加入购物车
  const addCart = async (product, amount = 1, price = "") => {
    await addToCratAPI({
      product,
      amount,
      price,
    });
    loadCart();
  };
  // 删除购物车数据
  const delCart = async (id) => {
    await delFromCartAPI(id);
    loadCart();
  };
  // 加载购物车数据
  const loadCart = async () => {
    const res = await loadCartAPI();
    carts.value = res.data;
  };
  // 计算购物车列表商品数量
  const cartCount = computed(() =>
    carts.value.reduce((pre, cur) => pre + cur.amount, 0)
  );
  //没有登录重置数据
  const resetCart = () => {
    carts.value = [];
  };
  return {
    carts,
    addCart,
    loadCart,
    cartCount,
    delCart,
    resetCart,
  };
});
